package com.eportal.filter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.eportal.domain.Sysopt;
import com.eportal.util.MD5;
import com.eportal.util.WebUtil;

public class AuthenticationFilter implements Filter {
	
	public final static String  SERVER_NAME_LOCK="login.yahlj.com";
	
	public final static String  SERVER_NAME_COMMUNITY="sq.yahlj.com";
	
	public final static String  SERVER_NAME_OTHER="localhost,121.40.204.191,127.0.0.1";
	
	public final static String  LOGIN_URL_LOCK="/admin/login.action";
	
	public final static String  LOGIN_URL_COMMUNITY="/admin/zlindex.action?loginFlag=login";
	
	

    private Logger logger = Logger.getLogger(this.getClass().getName());

    public static Map<String, Object> systemParam;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    	StringEscapeUtils.escapeSql("");
    	
        systemParam = new HashMap<String, Object>();
        try {
            String path = this.getClass().getClassLoader().getResource("/permission_config.xml").getPath();
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(path));
            List<Element> paramNodes = document.selectNodes("//param");
            for (Element n : paramNodes) {
                String key = n.attributeValue("name");
                String value;
                StringBuffer sb = new StringBuffer();
                Element e = n.element("values");
                if (e != null) {
                    List<Element> values = e.selectNodes("value");
                    for (Element v : values) {
                        sb.append(v.getText() + ",");
                    }
                    value = sb.substring(0, sb.length() - 1);
                } else {
                    e = n.element("value");
                    sb.append(e.getText());
                    value = sb.toString();
                }
                systemParam.put(key, value);
            }
            // 设置默认账户
           /* List<Element> accounts = document.selectNodes("//account");
            if (accounts.size() == 0) {
                Element account = document.getRootElement().addElement("account");
                Element name = account.addElement("userName");
                name.setText("admin");
                Element password = account.addElement("passwd");
                password.setText(MD5.MD5Encode(MD5.MD5Encode("123456")));
                Element roleId = account.addElement("roles");
                roleId.setText("1");
                Element realName = account.addElement("realName");
                realName.setText("SYSTEM");
                Element phone = account.addElement("phone");
                phone.setText("");
                Element isAdmin = account.addElement("isAdmin");
                isAdmin.setText("-1");
                OutputFormat format = OutputFormat.createPrettyPrint();
                XMLWriter writer = new XMLWriter(new FileOutputStream(path), format);
                writer.write(document);// 将文档写入到输出流
                writer.close();
            }*/
        } catch (Exception e) {
            logger.error("加载系统默认配置文件失败", e);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        String access = (String) systemParam.get("access");
        if (!uri.contains("static/") && uri.contains("admin")) {
            if (!access.contains(uri)) {
                HttpSession session = req.getSession();
                Sysopt user = (Sysopt) session.getAttribute("user");
                HttpServletResponse resp = (HttpServletResponse) response;
                if (user == null) {
                    if (uri.contains("admin")) {
                    	String serverName = req.getServerName();
                    	if(SERVER_NAME_LOCK.equals(serverName)){//锁厂域名跳转至锁厂登录页
                    		resp.sendRedirect(AuthenticationFilter.LOGIN_URL_LOCK);	
                    	}else if(SERVER_NAME_COMMUNITY.equals(serverName)){
                    		resp.sendRedirect(AuthenticationFilter.LOGIN_URL_COMMUNITY);
                    	}else if(SERVER_NAME_OTHER.indexOf(serverName)>-1){
                    		resp.sendRedirect(AuthenticationFilter.LOGIN_URL_COMMUNITY);
                    	}else{
                    		resp.sendRedirect("404.htm");	
                    	}
                    } else {
                        resp.sendRedirect("404.htm");
                    }
                    return;
                } else {
                    if(!user.getRoles().equals("0")){
                        Map<String, Object> map = (Map<String, Object>) session.getAttribute("auths");
                        String auths = (String) map.get("auths");
                        if (auths.indexOf(uri) < 0) {
                        	logger.info("no auth,"+uri);
                            resp.sendRedirect("404.htm");
                            return;
                        }
                        
                    }
                }
            }
        }
        if(uri.endsWith("ueditor/jsp/controller.jsp")){
        	chain.doFilter(new StrutsRequestWrapper((HttpServletRequest) req), response);
        }else if(uri.indexOf("/upload/notice/")>-1 || uri.indexOf("/upload/fix/")>-1){
        	chain.doFilter(request, response);
        }else{
        	chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
